<template>
  <div v-loading="loading">
    <el-form ref="form" :model="form" :rules="rules" label-width="120px" class="dataForm">
      <el-row>
        <el-col v-if="useProcess" :span="24">
          <el-form-item :label="$t('申请标题')" prop="actTitle">
            <el-input
              v-model="form.actTitle"
              :placeholder="$t('申请标题')"
              show-word-limit
              :maxlength="100"
            />
          </el-form-item>
        </el-col>
        <el-col v-if="!this.$route.query.id" :span="12">
          <el-form-item :label="$t('基金名称')" prop="fundId">
            <MainBodySelect
              v-model="form.fundId"
              parameters="fund"
              :disabled="this.$route.query.id"
              @change="fundChange"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('Call款期次')" prop="callPeriod">
            <el-input v-model="form.callPeriod" :placeholder="$t('Call款期次')" show-word-limit maxlength="100" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('Call款类型')" prop="callType">
            <el-select v-model="form.callType" value="" :placeholder="$t('Call款类型')">
              <el-option
                v-for="dict in callTypeOptions"
                :key="dict.dictValue"
                :label="$t(dict.dictLabel)"
                :value="dict.dictValue"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('Call款时间')" prop="callDate">
            <DatePicker
              v-model="form.callDate"
              :placeholder="$t('Call款时间')"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('Call款金额') + $t('金额单位')" prop="callMoney">
            <Money v-model="form.callMoney" unit="w" :placeholder="$t('Call款金额')" @change="changeCallDetail(-1)" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('Call款通知日期')" prop="noticeCallDate">
            <DatePicker
              v-model="form.noticeCallDate"
              type="date"
              :placeholder="$t('Call款通知日期')"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('Call款截止日期')" prop="callDateEnd">
            <DatePicker
              v-model="form.callDateEnd"
              type="date"
              :placeholder="$t('Call款截止日期')"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item prop="fundTotalSubscription">
            <span slot="label">
              {{ $t('基金总认缴') }}{{ $t('金额单位') }}
              <el-tooltip :content="$t('当前基金出资人认缴之和')" placement="top">
                <i class="el-icon-question" />
              </el-tooltip>
            </span>
            <money v-model="form.fundTotalSubscription" :placeholder="$t('基金总认缴')" unit="w" :disabled="true" />
          </el-form-item>
        </el-col>
        <!--        <el-col :span="12">-->
        <!--          <el-form-item prop="currency">-->
        <!--            <span slot="label">-->
        <!--              {{ $t('币种') }}-->
        <!--              <el-tooltip :content="$t('当前基金创建时指定的币种 (基金基本信息下的币种)')" placement="top">-->
        <!--                <i class="el-icon-question" />-->
        <!--              </el-tooltip>-->
        <!--            </span>-->
        <!--            <el-select v-model="form.currency" value="" :placeholder="$t('币种')" disabled>-->
        <!--              <el-option-->
        <!--                v-for="dict in currencyOptions"-->
        <!--                :key="dict.dictValue"-->
        <!--                :label="$t(dict.dictLabel)"-->
        <!--                :value="dict.dictValue"-->
        <!--              />-->
        <!--            </el-select>-->
        <!--          </el-form-item>-->
        <!--        </el-col>-->
        <el-col :span="12">
          <el-form-item prop="thisCallProportion">
            <span slot="label">
              {{ $t('本次Call占认缴比例(%)') }}
              <el-tooltip :content="$t('本次Call款金额除以所有出资人认缴总额')" placement="top">
                <i class="el-icon-question" />
              </el-tooltip>
            </span>
            <Ratio v-model="form.thisCallProportion" :placeholder="$t('本次call占认缴比例(%)')" disabled />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('Call款进度(%)')" prop="payCallProportion">
            <span slot="label">
              {{ $t('Call款进度(%)') }}
              <el-tooltip :content="$t('已Call款金额除以出资人认缴之和')" placement="top">
                <i class="el-icon-question" />
              </el-tooltip>
            </span>
            <Money v-model="form.payCallProportion" :placeholder="$t('Call款进度(%)')" disabled />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item :label="$t('备注')" prop=" remark">
            <el-input v-model="form.remark" type="textarea" maxlength="2000" :placeholder="$t('备注')" />
          </el-form-item>
        </el-col>
      </el-row>

      <!-- Call款项目 -->
      <div class="area-header" style="margin-top: 20px;">
        <span class="area-header-title">{{ $t('Call款项目') }}</span>
      </div>
      <el-table :data="form.fundCallMoneyDealList" border class="nowrapTable formTable">
        <el-table-column :label="$t('序号')" align="center" width="50">
          <template slot-scope="scope">
            {{ scope.$index + 1 }}
          </template>
        </el-table-column>
        <el-table-column :label="$t('项目名称')" align="center">
          <template slot="header" slot-scope="{}">
            <i style="color: #ff4949;margin-right: 4px;">*</i>
            <span>{{ $t('项目名称') }}</span>
          </template>
          <template slot-scope="scope">
            <el-form-item :prop="'fundCallMoneyDealList.' + scope.$index + '.dealId'" :rules="fundCallMoneyDealListRules.dealId">
              <el-select v-model="scope.row.dealId" :placeholder="$t('请选择项目')" @change="changeMoneys(scope.$index, scope.row.dealId)">
                <el-option
                  v-for="dict in investmentPortfolioDict"
                  :key="dict.dictValue"
                  :label="dict.dictLabel"
                  :value="dict.dictValue"
                />
              </el-select>
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column :label="$t('预计投资金额') + $t('金额单位')" align="center">
          <template slot="header" slot-scope="{}">
            <span>{{ $t('预计投资金额') }}{{ $t('金额单位') }}</span>
          </template>
          <template slot-scope="scope">
            <el-form-item :prop="'fundCallMoneyDealList.' + scope.$index + '.estimatedInvestmentAmount'" :rules="fundCallMoneyDealListRules.estimatedInvestmentAmount">
              <Money v-model="scope.row.estimatedInvestmentAmount" unit="w" disabled />
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column :label="$t('累计实际划款金额') + $t('金额单位')" align="center">
          <template slot="header" slot-scope="{}">
            <span>{{ $t('累计实际划款金额') }}{{ $t('金额单位') }}</span>
          </template>
          <template slot-scope="scope">
            <el-form-item :prop="'fundCallMoneyDealList.' + scope.$index + '.accumulatedActualTransferAmount'" :rules="fundCallMoneyDealListRules.accumulatedActualTransferAmount">
              <Money v-model="scope.row.accumulatedActualTransferAmount" unit="w" disabled />
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column :label="$t('本次Call款金额') + $t('金额单位')" align="center">
          <template slot="header" slot-scope="{}">
            <span>{{ $t('本次Call款金额') }}{{ $t('金额单位') }}</span>
          </template>
          <template slot-scope="scope">
            <el-form-item :prop="'fundCallMoneyDealList.' + scope.$index + '.amountThisCall'" :rules="fundCallMoneyDealListRules.amountThisCall">
              <Money v-model="scope.row.amountThisCall" unit="w" />
            </el-form-item>
          </template>
        </el-table-column>

        <el-table-column :label="$t('操作')" align="center" width="60px">
          <template slot-scope="scope">
            <el-button v-hasPermi="['fund:callmoney:remove']" size="small" type="text" icon="el-icon-delete" @click="delCallDeal(scope.$index, scope.row)" />
          </template>
        </el-table-column>
      </el-table>
      <div v-if="!otherBtnHide" class="tol">
        <el-button v-hasPermi="['fund:callmoney:edit']" type="primary" icon="el-icon-plus" size="mini" @click="addCallDeal">{{ $t("添加") }}</el-button>
      </div>

      <!--Call款明细-->
      <div class="area-header" style="margin-top: 20px;">
        <span class="area-header-title">
          {{ $t('Call款明细') }}
          <span>
            : {{ form.callMoney === undefined || form.callMoney === null || form.callMoney === '' ? '0' : moneyFormat(form.callMoney, 'w') }}
            {{ $t('金额单位') }}
          </span>
        </span>
      </div>
      <el-table :data="form.fundCallMoneyDetailList" border class="nowrapTable formTable">
        <el-table-column :label="$t('序号')" align="center" width="50">
          <template slot-scope="scope">
            {{ scope.$index + 1 }}
          </template>
        </el-table-column>
        <el-table-column :label="$t('出资人名称')" align="center" min-width="150">
          <template slot="header" slot-scope="{}">
            <span>{{ $t('出资人名称') }}</span>
          </template>
          <template slot-scope="scope">
            {{ scope.row.investName }}
          </template>
        </el-table-column>
        <el-table-column :label="$t('认缴金额') + $t('金额单位')" align="center" min-width="120">
          <template slot="header" slot-scope="{}">
            <span>{{ $t('认缴金额') }}{{ $t('金额单位') }}</span>
          </template>
          <template slot-scope="scope">
            {{ moneyFormat(scope.row.payMoney, 'w') }}
          </template>
        </el-table-column>
        <el-table-column :label="$t('认缴剩余金额') + $t('金额单位')" align="center" min-width="120">
          <template slot="header" slot-scope="{}">
            <span>{{ $t('认缴剩余金额') }}{{ $t('金额单位') }}</span>
          </template>
          <template slot-scope="scope">
            {{ moneyFormat(scope.row.surplusMoney, 'w') }}
          </template>
        </el-table-column>
        <el-table-column :label="$t('认缴比例(%)')" align="center" min-width="120">
          <template slot="header" slot-scope="{}">
            <span>{{ $t('认缴比例(%)') }}</span>
          </template>
          <template slot-scope="scope">
            {{ (scope.row.payProp * 100).toFixed(2) }}%
          </template>
        </el-table-column>
        <el-table-column :label="$t('累计Call款金额') + $t('金额单位')" align="center" min-width="130">
          <template slot="header" slot-scope="{}">
            <span>{{ $t('累计Call款金额') }}{{ $t('金额单位') }}</span>
          </template>
          <template slot-scope="scope">
            {{ moneyFormat(scope.row.sumCallMoney, 'w') }}
          </template>
        </el-table-column>
        <el-table-column :label="$t('累计实缴金额') + $t('金额单位')" align="center" min-width="130">
          <template slot="header" slot-scope="{}">
            <span>{{ $t('累计实缴金额') }}{{ $t('金额单位') }}</span>
          </template>
          <template slot-scope="scope">
            {{ moneyFormat(scope.row.accumulatedAmountPid, 'w') }}
          </template>
        </el-table-column>
        <el-table-column v-if="isRate" :label="$t('累计实缴金额') + $t('RMB') + $t('金额单位')" align="center" min-width="130">
          <template slot="header" slot-scope="{}">
            <span>{{ $t('累计实缴金额') + $t('RMB') }}{{ $t('金额单位') }}</span>
          </template>
          <template slot-scope="scope">
            {{ moneyFormat(scope.row.accumulatedAmountPidRmb, 'w') }}
          </template>
        </el-table-column>
        <el-table-column v-if="form.id !== undefined && form.id !== '' && form.id !== null" :label="$t('剩余应缴金额') + $t('金额单位')" align="center" prop="remainingSubscription" min-width="130">
          <template slot="header" slot-scope="{}">
            <span>{{ $t('剩余应缴金额') }}{{ $t('金额单位') }}</span>
          </template>
          <template slot-scope="scope">
            {{ moneyFormat(scope.row.remainingSubscription, 'w') }}
          </template>
        </el-table-column>
        <el-table-column :label="$t('本次应缴金额') + $t('金额单位')" align="center" min-width="130">
          <template slot="header" slot-scope="{}">
            <i style="color: #ff4949;margin-right: 4px;">*</i>
            <span>{{ $t('本次应缴金额') }}{{ $t('金额单位') }}</span>
          </template>
          <template slot-scope="scope">
            <el-form-item :prop="'fundCallMoneyDetailList.' + scope.$index + '.thisCallMoney'" :rules="fundCallMoneyDetailListRules.thisCallMoney">
              <Money v-model="scope.row.thisCallMoney" unit="w" @change="checkThisCallMoneyMax(scope.row, scope.$index)" />
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column v-if="!otherBtnHide" :label="$t('操作')" fixed="right" align="center" class-name="small-padding fixed-width" min-width="100">
          <template slot="header" slot-scope="{}">
            <span>{{ $t('操作') }}</span>
          </template>
          <template slot-scope="scope">
            <el-button
              v-if="form.id !== undefined && form.id !== '' && form.id !== null"
              v-hasPermi="['fund:callmoney:edit']"
              size="small"
              type="text"
              calss="el-button el-button--primary el-button--mini"
              :disabled="scope.row.buttonStatus"
              @click="contribution(scope.row)"
            >{{ $t('缴款') }}</el-button>
            <el-button
              v-hasPermi="['fund:callmoney:remove']"
              size="small"
              type="text"
              calss="el-button el-button--primary el-button--mini"
              @click="deleteCallDetail(scope.$index, scope.row)"
            >
              {{ $t('删除') }}
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <FileTable :list.sync="form.fileList" data-type="fund_call_money" :btn-show="!otherBtnHide" />
    </el-form>
    <!-- 添加或修改出资人缴款对话框 -->
    <el-dialog :title="title" :visible.sync="fundLpPaymentLoading" :close-on-click-modal="false" :lock-scroll="false" custom-class="dialogForm" append-to-body>
      <fundLpPaymentForm ref="fundLpPaymentForm" />
    </el-dialog>

    <el-dialog :title="$t('公示内容')" :visible.sync="publicityOpen" :destroy-on-close="true" :close-on-click-modal="false" :lock-scroll="false" custom-class="dialogForm" append-to-body>
      <afficheForm v-if="publicityOpen" ref="afficheForm" :call-init-status="callInitStatus" :call-money-use-process="useProcess" :show-save-btn="form.actStatus !== 'W' && form.actStatus !== 'D'" @bindToFundCall="bindToFundCall" />
    </el-dialog>

    <el-dialog :title="$t('公告审核')" :visible.sync="emailReviewOpen" :destroy-on-close="true" :close-on-click-modal="false" :lock-scroll="false" custom-class="dialogForm" append-to-body>
      <emailReviewForm v-if="emailReviewOpen" ref="emailReviewForm" :show-btn-status="form.actStatus !== 'W' && form.actStatus !== 'D'" />
    </el-dialog>

    <div slot="footer" class="dialog-footer" style="left: 0;">
      <!--      <el-button-->
      <!--        v-if="form.actStatus !== 'W' && form.actStatus !== 'D' && form.id !== undefined && form.id !== null && form.id !== ''"-->
      <!--        v-hasPermi="['fund:callmoney:edit']"-->
      <!--        icon="el-icon-s-promotion"-->
      <!--        type="success"-->
      <!--        @click="sendHandle(form)"-->
      <!--      >{{ $t('通知配置') }}</el-button>-->
      <el-button
        v-if="(form.actStatus === 'W' || form.actStatus === 'D') && form.announcementId"
        icon="el-icon-s-promotion"
        type="success"
        @click="noticeHandle(form)"
      >{{ $t('通知详情') }}</el-button>
      <!--计算规则-->
      <el-button v-if="(form.actStatus !== 'W' && form.actStatus !== 'D') || !useProcess" type="warning" @click="changeResultRadio(1)">{{ $t('按总认缴计算') }}</el-button>
      <el-button v-if="(form.actStatus !== 'W' && form.actStatus !== 'D') || !useProcess" type="warning" style="margin-right: 10px;" @click="changeResultRadio(2)">{{ $t('按剩余认缴计算') }}</el-button>
    </div>
    <div slot="footer" class="dialog-footer" style="text-align: right;">
      <!-- 使用流程：保存，保存并启动流程，取消 三个按钮-->
      <FormBtn v-if="useProcess" ref="formBtn" :bus-data="form" has-permi="fund:callmoney" :menu-key="menuKey" :cancel-show="saveButton" :cancel-func="cancel" :save-show="saveButton" :btn-hide="btnHide" />
      <!--未使用流程：保存 取消按钮-->
      <SaveBtn v-if="!useProcess" has-permi="fund:callmoney" :cancel-show="saveButton" :save-show="saveButton" />
    </div>
  </div>
</template>

<script>
    import { findDeal } from '@/api/base/deal/dealBase'
    import { findInvestPortfolio, getFundBase, getFundName } from '@/api/fund/fundBase'
    import { saveFundCallMoney,
             getFundCallMoney,
             delFundCallMoneyDeal,
             getFundCallMoneyInvest,
             findDealInvestByDealId,
             getByFundIdInit,
             getCallMoneySumByFundId,
             removeRepetitionByName,
             delFundCallMoneyDetail
           } from '@/api/fund/callmoney/fundCallMoney'
    import { findLpViewGetInvest } from '@/api/fund/investor/fundInvestor'
    import { getSystemCurrency } from '@/api/system/config'
    import { getMenuProcess } from '@/api/act/process/wfMenuProcess'
    import { updateReviewStatus } from '@/api/fund/lpBase/lp/affiche/affiche'
    import { ruoyiFloat } from '@/utils/ruoyi'
    import MainBodySelect from '@/components/MainBodySelect/index'
    import fundLpPaymentForm from '@/views/fund/lpPayment/fundLpPaymentForm'
    import afficheForm from '@/views/fund/lpBase/lp/afficheForm.vue'
    import emailReviewForm from '@/views/fund/lpBase/lp/EmailReviewForm'
    import { existBusinessId } from '@/api/fund/lpBase/lp/affiche/afficheListTemplate'
    export default {
        components: {
          emailReviewForm,
          afficheForm,
          fundLpPaymentForm,
          MainBodySelect
        },
        data() {
            const checkRules = (rule, value, callback) => {
              try {
                var reg = /[`~!@#$%^&*_\-=<>?:"{}|.\/;'\\[\]·~！@#￥%……&——\-={}|《》？：“”【】、；‘'。、]/im
                if (value === undefined || value === '' || value === null) {
                  callback(new Error(this.$t('必填信息')))
                } else if (reg.test(value)) {
                  callback(new Error('不能包含特殊字符'))
                } else {
                  if (this.isUpdateName === false) {
                    var flag = false

                    var fundId = this.$route.query.id === undefined ? this.form.fundId : this.$route.query.id
                    if (fundId === undefined) {
                      fundId = this.form.fundId
                    }
                    if (fundId === undefined || fundId === '' || fundId === null) {
                      this.form.callPeriod = undefined
                      callback(new Error(this.$t('先选择基金')))
                    } else {
                      removeRepetitionByName(value, fundId).then(response => {
                        flag = response.data
                        if (!flag) {
                          callback(new Error(this.$t('已存在该Call款期次')))
                        } else {
                          callback()
                        }
                      })
                    }
                  } else {
                    callback()
                  }
                }
              } catch (e) {
                console.log(e)
                callback()
              }
            }
            // 校验call通知日期
            const callStopCheck = (rule, value, callback) => {
              console.log(rule, value, callback)
              var start = ''
              var end = ''
              // Call款时间
              var callDate = (this.form.callDate === undefined || this.form.callDate === null || this.form.callDate === '') ? undefined : this.form.callDate
              // 通知Call款日期
              var noticeCallDate = (this.form.noticeCallDate === undefined || this.form.noticeCallDate === null || this.form.noticeCallDate === '') ? undefined : this.form.noticeCallDate
              // Call款截止日
              var callDateEnd = (this.form.callDateEnd === undefined || this.form.callDateEnd === null || this.form.callDateEnd === '') ? undefined : this.form.callDateEnd
              var flagCount = 0
              if (noticeCallDate && callDateEnd) {
                start = noticeCallDate.substring(0, 10)
                end = callDateEnd.substring(0, 10)
                if (new Date(start).getTime() > new Date(end).getTime()) {
                  callback(new Error(this.$t('Call款截止日期不能早于Call款通知日期!')))
                } else {
                  flagCount++
                }
              }
              if (callDate && callDateEnd) {
                start = callDate.substring(0, 10)
                end = callDateEnd.substring(0, 10)
                if (new Date(start).getTime() > new Date(end).getTime()) {
                  callback(new Error(this.$t('Call款截止日期不能早于Call款时间!')))
                } else {
                  flagCount++
                }
              } else {
                callback()
              }
              if (flagCount >= 2) {
                callback()
              } else if (this.isEmpty(noticeCallDate)) {
                callback()
              }
            }
            return {
                otherBtnHide: false,
                // 是否隐藏保存按钮
                btnHide: false,
                title: undefined,
                // 菜单标识
                menuKey: 'fund_investor_call',
                // 表单参数
                form: {
                  fileList: []
                },
                // 遮罩层
                loading: false,
                fundCurr: '',
                defCurr: '',
                isRate: false,
                fundLpPaymentLoading: false,
                saveButton: true,
                // 表单校验
                rules: {
                  actTitle: [{ required: true, message: this.$t('必填信息'),	trigger: 'blur' }],
                  callPeriod: [{ required: true, validator: checkRules,	trigger: 'blur' }],
                  callType: [{ required: true, message: this.$t('必填信息'),	trigger: 'blur' }],
                  callDate: [{ required: true, message: this.$t('必填信息'),	trigger: 'blur' }],
                  callMoney: [{ required: true, message: this.$t('必填信息'),	trigger: 'blur' }],
                  fundId: [{ required: true, message: this.$t('必填信息'),	trigger: ['blur', 'change'] }],
                  callDateEnd: [{ required: false, validator: callStopCheck, trigger: ['blur', 'change'] }]
                },
                fundCallMoneyDealListRules: {
                  dealId: [{ required: true, message: this.$t('必填信息'),	trigger: 'blur' }]
                },
                fundCallMoneyDetailListRules: {
                  thisCallMoney: [{ required: true, message: this.$t('必填信息'),	trigger: 'blur' }]
                },
                // Call款类型
                callTypeOptions: [],
                // 币种字典
                // currencyOptions: [],
                // Call款项目
                fundCallMoneyDealList: [],
                // Call款明细
                fundCallMoneyDetailList: [],
                dealList: [],
                // 投资组合
                investmentPortfolioDict: [],
                // 能否修改期次名称
                isUpdateName: false,
                // 第一次不触发fundChange
                flagChange: false,
                // 新添加Call款时, 删除的Call款人 id临时记录用于计算
                excludingInvestorsId: [],
                // 修改时. 第一次走这个方法掠过.
                firstLoadingCount: 0,
                resultRadio: 0,
                // 是否配置了流程
                useProcess: false,
                publicityOpen: false,
                emailReviewOpen: false,
                callInitStatus: true
            }
        },
        watch: {
        },
        created() {
          this.$bus.$emit('async_done')
          this.getDicts('fund_call_type').then(response => {
            this.callTypeOptions = response.data
          })
          // 查询项目
          findDeal().then(response => {
            this.dealList = response.data
          })
          if (this.$route.query.id) {
            this.initCurr()
            // Call款项目 项目名称下拉
            const fundId = this.$route.query.id === undefined ? this.form.fundId : this.$route.query.id
            this.callDealSelect(fundId)
          }
          this.getUseProcess()
        },
        methods: {
            // 初始化数据
            init(data) {
                if (data && data.formId) {
                  this.saveButton = false
                }
                this.loading = true
                this.firstLoadingCount = 0
                if (data != null && data.id !== undefined) {
                    this.isUpdateName = true
                    getFundCallMoney(data.id).then(response => {
                        this.form = response.data
                        if (!this.$route.query.id) {
                          // Call款项目 项目名称下拉
                          this.callDealSelect(this.form.fundId)
                        }
                        this.loading = false
                    })
                } else {
                    this.isUpdateName = false
                    this.reset()
                  if (data != null) {
                    this.form.fileList = data.fileList
                  }
                    if (this.$route.query.id) {
                      this.initData(this.$route.query.id)
                    } else {
                      this.loading = false
                    }
                }
            },
            // 表单重置
            reset() {
                this.form = {
                id: undefined,
                fundId: this.$route.query.id,
                callPeriod: undefined,
                callType: undefined,
                callDate: undefined,
                callMoney: undefined,
                noticeCallDate: undefined,
                callDateEnd: undefined,
                fundTotalSubscription: undefined,
                currency: undefined,
                thisCallProportion: undefined,
                payCallProportion: undefined,
                resultRadio: 0,
                remark: undefined,
                createBy: undefined,
                createTime: undefined,
                updateBy: undefined,
                updateTime: undefined,
                delFlag: undefined,
                fundCallMoneyDealList: [],
                fundCallMoneyDetailList: [],
                  fileList: []
                }
                this.resetForm('form')
            },

            // 关闭form页面
            closeForm() {
              console.log('关闭')
              // 关闭form页面遮罩层
              this.loading = false
              // 关闭form页面
              if (this.$parent.$parent.formCallOpen !== undefined) {
                this.$parent.$parent.formCallOpen = false
              }
              // 刷新list页面
              if (this.$parent.$parent.getList !== undefined) {
                this.$parent.$parent.getList()
              }
            },
            cancel() {
              console.log('取消')
              // 关闭form页面遮罩层
              this.loading = false
              // 关闭form页面
              if (this.$parent.$parent.formCallOpen !== undefined) {
                this.$parent.$parent.formCallOpen = false
              }
              if (this.$parent.$parent.formOpen) {
                this.$parent.$parent.formOpen = false
              }
            },
            /** 提缴按钮 */
            submitForm: function(type) {
              return new Promise((resolve, reject) => {
                this.$refs['form'].validate(valid => {
                    if (valid) {
                        this.loading = true
                        // 新增数据时 如果没有配置流程，则将审批状态设置为审批完成
                        if (!this.useProcess && !this.form.id) {
                          this.form.actStatus = 'W'
                        }
                        var temp = this.form.fundCallMoneyDetailList
                        var thisCallMoneySum = 0
                        if (temp !== null && temp !== '' && temp !== undefined) {
                            temp.forEach(item => {
                              if (item.thisCallMoney === undefined || item.thisCallMoney === '' || item.thisCallMoney === null || isNaN(item.thisCallMoney)) {
                                item.thisCallMoney = 0
                              }
                              thisCallMoneySum += ruoyiFloat().formatNum(item.thisCallMoney)
                            })
                        }
                        var moneyTemp1 = ruoyiFloat().formatNum(this.form.callMoney).toFixed(5)
                        var moneyTemp2 = ruoyiFloat().formatNum(thisCallMoneySum).toFixed(5)
                        if (ruoyiFloat().formatNum(moneyTemp1) !== ruoyiFloat().formatNum(moneyTemp2)) {
                          console.error('金额比较不相等, Call款总额为:' + ruoyiFloat().formatNum(moneyTemp1) + ', Call款明细总额为:' + ruoyiFloat().formatNum(moneyTemp2))
                          this.msgError(this.$t('Call款金额与Call款明细中本次应交金额之和不相等, 请检查!'))
                          this.loading = false
                        } else {
                          this.loading = true
                          saveFundCallMoney(this.form).then(response => {
                            if (response.code === 200) {
                              this.form = response.data
                              this.isUpdateName = true
                              if (type === 'process') {
                                // 设置数据id方式启动流程后取消并再次启动会创建多条记录
                                const responseData = response.data
                                if (responseData.announcementId === undefined || responseData.announcementId === null || responseData.announcementId === '') {
                                  this.loading = false
                                  this.$confirm(this.$t('未设置公告, 是否跳转?'), this.$t('提示'), {
                                    confirmButtonText: this.$t('跳转'),
                                    cancelButtonText: this.$t('取消'),
                                    type: 'warning'
                                  }).then(() => {
                                    setTimeout(() => {
                                      this.sendHandle(responseData)
                                    }, 500)
                                    this.startProcess(response.data)
                                  }).catch(() => {
                                    // 启动流程
                                    this.startProcess(response.data)
                                  })
                                } else {
                                  // 启动流程
                                  this.startProcess(response.data)
                                }
                              } else {
                                // 点击的仅保存
                                this.msgSuccess(this.$t('保存成功'))
                                // 关闭form页面
                                this.closeForm()
                              }
                              resolve(response.data.id)
                            } else {
                              this.msgError(response.msg)
                              this.loading = false
                              reject(response)
                            }
                          }).catch(() => {
                            this.loading = false
                          })
                        }
                    } else {
                      this.locationError(document)
                      reject()
                    }
                })
              })
            },
            // 启动流程
            startProcess: async function(data) {
              var _this = this
              var fundName = await getFundName(this.$route.query.id)
              this.loading = false
              // 启动流程时候传入的参数
              const processData = {}
              // 待办标题
              processData.title = '「' + fundName + '」' + ' - ' + this.$t('基金Call款') + ': ' + this.form.actTitle
              // 业务表名
              processData.dataTable = 'fund_call_money'
              // 业务ID
              processData.dataId = data.id
              // 业务表单地址(待办页面需要打开的页面)
              processData.formPath = this.useProcess ? '@/views/fund/callmoney/fundCallMoneyProcess' : '@/views/fund/callmoney/fundCallMoneyForm'
              processData.viewPath = this.useProcess ? '@/views/fund/callmoney/fundCallMoneyProcess' : '@/views/fund/callmoney/fundCallMoneyForm'
              // 菜单标识(根据菜单标识判断的走哪个流程)
              processData.menuKey = this.menuKey
              this.startProcessByMenu(processData, () => {
                debugger
                console.log(processData, _this)
                this.form.actStatus = 'D'
                if (_this.form.announcementId !== undefined && _this.form.announcementId !== null && _this.form.announcementId !== '') {
                  updateReviewStatus(_this.form.announcementId, '待复核')
                }
                this.msgSuccess(this.$t('数据保存成功,流程启动成功'))
                this.closeForm()
              })
            },
            // afficheForm在首次保存并启动流程后, 跳转到通知页面进行新增, 新增完了需要把ID穿到当前表单的form.ann..Id里
            bindToFundCall(data) {
              this.form.announcementId = data.id
            },
            // 添加Call款项目
            addCallDeal() {
              const row = {
                id: undefined,
                dealId: undefined,
                estimatedInvestmentAmount: undefined,
                accumulatedActualTransferAmount: undefined,
                amountThisCall: undefined,
                remark: undefined
              }
              if (!(this.form.fundCallMoneyDealList instanceof Array)) {
                this.$set(this.form, 'fundCallMoneyDealList', [])
              }
              this.$nextTick(() => {
                this.form.fundCallMoneyDealList.push(row)
              })
            },
            // 删除Call款项目
            delCallDeal(index, row) {
              const id = row.id
              if (id !== undefined && id !== '' && id != null) {
                this.$confirm(this.$t('是否确认删除?'), this.$t('警告'), {
                  confirmButtonText: this.$t('确定'),
                  cancelButtonText: this.$t('取消'),
                  type: 'warning'
                })
                  .then(function() {
                    return delFundCallMoneyDeal(id)
                  }).then(() => {
                  this.form.fundCallMoneyDealList.splice(index, 1)
                  return this.msgSuccess(this.$t('删除成功'))
                })
                  .catch(function() {
                  })
              } else {
                this.form.fundCallMoneyDealList.splice(index, 1)
              }
            },
            changeMoneys(index, dealId) {
              const fundId = this.$route.query.id === undefined ? this.form.fundId : this.$route.query.id
              findDealInvestByDealId(dealId, fundId).then(response => {
                if (response.data === null) {
                  // 预计投资金额
                  this.form.fundCallMoneyDealList[index].estimatedInvestmentAmount = '0'
                  // 累计实际投资金额
                  this.form.fundCallMoneyDealList[index].accumulatedActualTransferAmount = '0'
                } else {
                  // 预计投资金额
                  this.form.fundCallMoneyDealList[index].estimatedInvestmentAmount = response.data.amountInvestmentEstimate
                  // 累计实际投资金额
                  this.form.fundCallMoneyDealList[index].accumulatedActualTransferAmount = response.data.amountInvestmentFact
                }
              })
            },
            contribution(row) {
              let sumThisCallMoney = 0
              this.form.fundCallMoneyDetailList.forEach(item => {
                sumThisCallMoney += Number(item.thisCallMoney)
              })
              this.fundLpPaymentLoading = true
              this.title = this.$t('添加出资人缴款')
              this.$nextTick(() => {
                this.$refs.fundLpPaymentForm.init(null)
                // 出资人名称
                const fundId = this.$route.query.id === undefined ? this.form.fundId : this.$route.query.id
                findLpViewGetInvest(row.investId, fundId).then(response => {
                  this.$refs.fundLpPaymentForm.form.investId = response.data.id
                  this.$refs.fundLpPaymentForm.form.fundId = fundId
                  // 期次
                  this.$refs.fundLpPaymentForm.form.callPeriod = row.fundCallMoneyId
                  // 认缴
                  this.$refs.fundLpPaymentForm.form.subscriptionAmount = row.payMoney
                  // Call款金额
                  this.$refs.fundLpPaymentForm.form.callMoney = sumThisCallMoney
                  // 已缴金额
                  this.$refs.fundLpPaymentForm.form.amountPaid = sumThisCallMoney - row.remainingSubscription
                  // 剩余金额
                  this.$refs.fundLpPaymentForm.form.amountRemaining = row.remainingSubscription
                  // 本次应缴金额 带到 缴款金额
                  try {
                    this.$refs.fundLpPaymentForm.form.payMoney = row.remainingSubscription
                  } catch (e) {
                    console.log(e)
                  }
                  this.$refs.fundLpPaymentForm.isShowCallInfo = true
                })
              })
            },
            // Call款金额输入后自动计算Call款明细的本次应缴金额
            changeCallDetail(resultRadio) {
              if (resultRadio !== '0' && resultRadio !== 0) {
                var money = this.form.callMoney
                if (this.utilsCheckNotNUll(money)) {
                  var fundIdTemp = this.$route.query.id === undefined ? this.form.fundId : this.$route.query.id
                  getCallMoneySumByFundId(fundIdTemp).then(response => {
                    var tempMoneys = 0
                    if (this.utilsCheckNotNUll(this.form.id)) {
                      tempMoneys = response.data
                    } else {
                      tempMoneys = money + response.data
                    }
                    if (tempMoneys > this.form.fundTotalSubscription) {
                      // 这里判断当前Call款金 + 历史Call款金额总和是否大于 基金总认缴
                      var tempMoney = response.data / 10000
                      if (tempMoney === 0) {
                        this.msgError(this.$t('Call款金额不能超过基金总认缴'))
                      } else {
                        this.msgError(this.$t('Call款金额已达') + tempMoney + this.$t('万元') + ',' + (this.$t('不能超过基金总认缴')))
                      }
                      this.form.callMoney = 0
                    } else {
                      // 四个问号 的 本次Call款比例
                      try {
                        this.form.thisCallProportion = (this.form.callMoney / this.form.fundTotalSubscription) * 100
                      } catch (e) {
                        console.log(e)
                      }
                      // 判断call明细
                      var array = this.form.fundCallMoneyDetailList
                      array.forEach(item => {
                        item.thisCallMoney = 0
                      })
                      var investorsTempId = this.excludingInvestorsId
                      if (array !== '' && array !== null && array !== undefined) {
                        for (var i = 0; i < array.length; i++) {
                          if (investorsTempId !== null && investorsTempId !== '' && investorsTempId !== undefined) {
                            investorsTempId.forEach(item2 => {
                              if (array[i].investId === item2.investId) {
                                array.splice(i, 1)
                              }
                            })
                          }
                        }
                      }
                      if (money !== undefined && money !== '' && money !== null) {
                        // 根据每个出资人的认缴比例计算本次应Call款金额
                        array && array.forEach((item, index) => {
                          // 最后一个出资人 的金额除不尽时 , 用总金额 - 以计算的本次应缴金额
                          var arrLength = array.length
                          if (index === arrLength) {
                            var sum = 0
                            array.forEach(temp => {
                              sum += parseFloat(temp.thisCallMoney)
                            })

                            if (resultRadio !== '0' && resultRadio !== 0) {
                              this.form.thisCallMoney = money - sum
                            } else {
                              this.form.thisCallMoney = 0
                            }
                          } else {
                            // 按总认缴计算本次应交金额
                            if (resultRadio === 1 || resultRadio === '1') {
                              item.thisCallMoney = (parseFloat(this.form.callMoney) * parseFloat(item.payProp)).toFixed(6)
                              item.thisCallMoney = ruoyiFloat().formatNum(item.thisCallMoney)
                            } else if (resultRadio === 2 || resultRadio === '2') {
                              // 按总剩余认缴计算本次应交金额
                              item.thisCallMoney = (parseFloat(this.form.callMoney) * parseFloat(item.payProp)).toFixed(6)
                            } else {
                              item.thisCallMoney = 0
                            }
                          }
                        })
                      }
                      // 判断本次应缴金额是否大于剩余认缴额
                      var message = ''
                      array && array.some(item => {
                        if (ruoyiFloat().formatNum(item.surplusMoney) < ruoyiFloat().formatNum(item.thisCallMoney)) {
                          item.thisCallMoney = 0
                          message += '<div>' + item.investName + ': ' + this.$t('剩余认缴不足请手动维护') + '</div>'
                        }
                      })
                      if (message !== '') {
                        this.$message({
                          dangerouslyUseHTMLString: true,
                          showClose: true,
                          message: '<div style="font-size: 14px;">' + message + '</div>'
                        })
                      }
                    }
                  })
                }
              } else {
                this.form.fundCallMoneyDetailList.forEach(item => {
                  item.thisCallMoney = 0
                })
              }
            },
            // 选择 Call款明细的 计算方式 计算出比例
            changeResultRadio(radio) {
              var array = this.form.fundCallMoneyDetailList
              // 每次切换认缴方式 都清空原有金额
              array && array.forEach(item => {
                item.thisCallMoney = 0
              })
              // 根据认缴总额计算
              if (radio === '1' || radio === 1) {
                // 计算所有出资人的认缴总额之和
                var tempPayMoney = 0
                array && array.forEach(item => {
                  tempPayMoney += item.payMoney
                })
                // 根据每个出资人算出他的认缴总额的比例
                var sum = 0
                array && array.forEach((item, index) => {
                  if (index === array.length - 1) {
                    item.payProp = 1 - sum
                  } else {
                    if (tempPayMoney === 0) {
                      item.payProp = 0
                    } else {
                      item.payProp = (item.payMoney / tempPayMoney).toFixed(15)
                    }
                    sum += Number(item.payProp)
                  }
                })
                // 计算出百分比后, 重新根据上面主表的Call款金额 计算子表的本次Call款金额
                this.changeCallDetail(radio)
              } else if (radio === '2' || radio === 2) {
                // 根据剩余认缴计算
                var tempSurplusMoney = 0
                array && array.forEach(item => {
                  tempSurplusMoney += item.surplusMoney
                })
                // 根据每个出资人算出他的认缴总额的比例
                var sum2 = 0
                array && array.forEach((item, index) => {
                  if (index === array.length - 1) {
                   item.payProp = 1 - sum2
                  } else {
                    if (tempSurplusMoney === 0) {
                      item.payProp = 0
                    } else {
                      item.payProp = (item.surplusMoney / tempSurplusMoney).toFixed(15)
                    }
                    sum2 += Number(item.payProp)
                  }
                })
                // 计算出百分比后, 重新根据上面主表的Call款金额 计算子表的本次Call款金额
                this.changeCallDetail(radio)
              }
            },
            utilsCheckNotNUll(data) {
              try {
                if (data !== undefined && data !== '' && data !== null) {
                  return true
                } else {
                  return false
                }
              } catch {
                return false
              }
            },
            toFixedNumber(value, count) {
              if (value === undefined) {
                return 0
              }
              value = value.replaceAll(',', '')
              return parseFloat(Number(value).toFixed(count))
            },
          // 新增时 初始化数据
          initData(fundId) {
            // 基金认缴总额 ....  四个问好 的数据引入
            getByFundIdInit(fundId).then(response => {
              this.form.fundTotalSubscription = response.data.fundTotalSubscription
              this.form.payCallProportion = response.data.payCallProportion
              this.form.currency = response.data.currency
              this.loading = false
            })
            // 默认带出 call明细中的出资人
            getFundCallMoneyInvest(fundId).then(response => {
              response.data.forEach(item => {
                const row = {
                  'investId': item.investId,
                  'investName': item.investName,
                  // 认缴金额 payMoney
                  'payMoney': item.payMoney,
                  // 认缴比例 payProp
                  'payProp': item.payProp,
                  // 认缴剩余金额 surplusMoney   // 认缴 - 累计实缴
                  'surplusMoney': item.surplusMoney,
                  // 累计Call款金额 sumCallMoney // 历史Call款
                  'sumCallMoney': item.sumCallMoney,
                  // 累计实缴金额
                  'accumulatedAmountPid': item.accumulatedAmountPid,
                  // 累计实缴') + $t('RMB')
                  'accumulatedAmountPidRmb': item.accumulatedAmountPidRmb,
                  // 剩余应缴金额
                  'remainingSubscription': item.thisCallMoney - item.remainingSubscription,
                  // 本次应缴金额
                  'thisCallMoney': item.thisCallMoney ? item.thisCallMoney : 0,
                  // 按钮是否禁用
                  'buttonStatus': item.buttonStatus
                }
                if (!(this.form.fundCallMoneyDetailList instanceof Array)) {
                  this.$set(this.form, 'fundCallMoneyDetailList', [])
                }
                this.$nextTick(() => {
                  this.form.fundCallMoneyDetailList.push(row)
                })
              })
              this.loading = false
            })
          },
          // Call款项目 项目名称下拉
          callDealSelect(fundId) {
            // Call款项目 项目名称下拉
            var query = { fundId: fundId }
            findInvestPortfolio(query).then(response => {
              this.investmentPortfolioDict = []
              response.rows.forEach(item => {
                var temp = { 'dictValue': item.dealId, 'dictLabel': item.itemName }
                this.investmentPortfolioDict.push(temp)
              })
            })
          },
          // 选择基金名称时 加载所选基金的数据
          fundChange(val) {
              if (val) {
                this.loading = true
                this.form.fundCallMoneyDetailList = undefined
                if (this.flagChange) {
                  this.form.fundCallMoneyDealList = undefined
                }
                this.flagChange = true
                this.callDealSelect(val)
                this.initData(val)
              }
          },
          // 删除Call款明细
          deleteCallDetail(index, row) {
            const id = row.id
            if (this.form.fundCallMoneyDetailList !== undefined && this.form.fundCallMoneyDetailList !== null && this.form.fundCallMoneyDetailList.length > 1) {
              if (id !== undefined && id !== null && id !== '') {
                this.$confirm(this.$t('是否确认删除?'), this.$t('警告'), {
                  confirmButtonText: this.$t('确定'),
                  cancelButtonText: this.$t('取消'),
                  type: 'warning'
                })
                .then(function() {
                  return delFundCallMoneyDetail(row.id)
                }).then(() => {
                // 重新计算本次认缴金额
                var tempInvestId = this.form.fundCallMoneyDetailList[index].investId
                this.form.fundCallMoneyDetailList.splice(index, 1)
                this.recalculateAmount(tempInvestId)
                return this.msgSuccess(this.$t('删除成功'))
                })
                .catch(function() {
                })
              } else {
                var tempInvestId = this.form.fundCallMoneyDetailList[index].investId
                this.form.fundCallMoneyDetailList.splice(index, 1)
                this.recalculateAmount(tempInvestId)
                return this.msgSuccess(this.$t('删除成功'))
              }
            } else {
              this.msgError(this.$t('至少保留一位出资人!'))
            }
          },
          // 重新计算本次认缴金额
          recalculateAmount(investId) {
            this.excludingInvestorsId.push(investId)
          },
          // 校验本次Call款金额 不能大于 剩余认缴金额
          checkThisCallMoneyMax(row, index) {
            console.log(index)
            const money = row.thisCallMoney
            const surplus = row.surplusMoney
            if (money > surplus) {
              var tempInvestName = row.investName
              this.msgError(this.$t('Call款明细') + tempInvestName + this.$t('不能大于剩余认缴金额'))
              this.form.fundCallMoneyDetailList[index].thisCallMoney = 0
              this.$set(this.form.fundCallMoneyDetailList[index], 'thisCallMoney', 0)
              this.$forceUpdate()
            }
            // 重新累计出 主表的Call款金额的总值
            const callDetail = this.form.fundCallMoneyDetailList
            if (callDetail !== undefined && callDetail !== null && callDetail !== '') {
              var sum = 0
              callDetail.forEach(item => {
                var thisCallMoney = parseFloat(item.thisCallMoney)
                if (thisCallMoney === undefined || thisCallMoney === '' || thisCallMoney === null || isNaN(thisCallMoney)) {
                  thisCallMoney = 0
                }
                sum += (thisCallMoney)
              })
              if (!(sum <= this.form.callMoney && sum > (this.form.callMoney - 1))) {
                this.form.callMoney = sum.toFixed(6)
                this.form.thisCallProportion = (this.form.callMoney / this.form.fundTotalSubscription) * 100
              }
            }
          },
          // 初始化币种信息
          async initCurr() {
            var fundIdTemp = this.$route.query.id === undefined ? this.form.fundId : this.$route.query.id
            await getFundBase(fundIdTemp).then(res => {
              this.fundCurr = res.data.currency
            })
            await getSystemCurrency().then(res => {
              if (res.code === 200) {
                this.defCurr = res.data
              } else {
                this.msgError(res.msg)
              }
            })
            this.isRate = this.defCurr !== this.fundCurr
          },
          // 审核公告
          noticeHandle() {
            this.emailReviewOpen = true
            this.$nextTick(() => {
              this.$refs.emailReviewForm.init({ id: this.form.announcementId })
            })
          },
          // 配置公告
          sendHandle(row) {
            this.publicityOpen = true
            this.callInitStatus = true
            this.$nextTick(() => {
              if (!this.isEmpty(row.announcementId)) {
                var fundId = this.$route.query.id === undefined ? this.queryParams.fundId : this.$route.query.id
                fundId = (fundId === undefined || fundId === '' || fundId === null) ? this.form.fundId : fundId
                existBusinessId({ businessId: fundId, businessType: 'callMoney', orgId: '3' }).then(response => {
                  if (response.data) {
                    this.$refs.afficheForm.init({ id: row.announcementId, fundId: row.fundId, type: response.data.id, callPeriod: row.callPeriod, dataId: row.id })
                  } else {
                    this.$refs.afficheForm.init({ id: row.announcementId, fundId: row.fundId, type: '3', callPeriod: row.callPeriod, dataId: row.id })
                  }
                })
              } else {
                this.updateSendHandle(row)
              }
            })
          },
          updateSendHandle(row) {
            // 判断当前基金是否存在模板不存在取默认的
            var fundId = this.$route.query.id === undefined ? this.queryParams.fundId : this.$route.query.id
            fundId = (fundId === undefined || fundId === '' || fundId === null) ? this.selectCallFundId : fundId
            existBusinessId({ businessId: fundId, businessType: 'callMoney', orgId: '3' }).then(response => {
              if (response.data) {
                this.$refs.afficheForm.reset()
                this.$refs.afficheForm.form.fundId = row.fundId
                this.$refs.afficheForm.form.callPeriod = row.id
                this.$refs.afficheForm.form.type = response.data.id
                this.$refs.afficheForm.dataChange(row.fundId)
              }
            })
          },
          // 获取是否使用流程
          getUseProcess() {
            // 根据基金ID区分使用基金流程还是SPV流程
            getFundBase(this.$route.query.id).then(res => {
              if (res && !this.isEmpty(res.data)) {
                if (res.data.dataType === 'spv' || res.data.dataType === 'SPV') {
                  this.menuKey = 'fund_investor_call_spv'
                }
              }
              getMenuProcess(this.menuKey).then(response => {
                this.useProcess = (response.data !== undefined && response.data !== null && response.data !== '')
              })
            })
          }

        }
    }
</script>
